package com.vnp.vchat.version2;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.net.ssl.SSLContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView.ScaleType;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.turbomanage.httpclient.HttpResponse;
import com.vnp.vchat.R;
import com.vnp.vchat.UIControls.MyCircleImageView;
import com.vnp.vchat.Util.Common;
import com.vnp.vchat.Util.DecodeUtils;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.adapter.ChatAdapter;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.bean.ObjMsgChat;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpBasicClientHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonAsyncCallback;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;

public class ChatNewActivity extends Activity implements OnTouchListener,
		OnClickListener {

	MySQLiteHelper db;
	PreferenceHelper preferenceHelper;
	Button btnBack, btnHoatdong;
	ImageView icOnline;
	ProgressBar progressBar;
	String hash;
	
	ViewGroup header;
	
	boolean onPause = false;
	boolean onFinish = false;
	boolean isNoti = false;
	public static boolean onShow;
	TextView txtSanpham;
	String url="", dsDaxem;
	
	boolean isNew = false;
	
	byte[] byteArray;
	String status = "";
	
	SocketIO socketIO;
	String URL = "http://w41.vnpgroup.net:8080";
	
	boolean isShowingBtnNew = false;
	
	// msg ko phai cua minh
	LinearLayout llNewMsg;
	TextView txtTen, txtMsg;
	Animation pullDown, pullUp, fadeIn, fadeOut;
	Runnable rShow = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					llNewMsg.setVisibility(View.VISIBLE);
					llNewMsg.startAnimation(pullDown);
				}
			});
			
		}
	};
	
	Runnable rHide = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					llNewMsg.setVisibility(View.GONE);
					llNewMsg.startAnimation(pullUp);					
				}
			});
			
		}
	};	
	
	Runnable rShowDangxuat = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					llDangxuat.setVisibility(View.VISIBLE);
				}
			});
			
		}
	};
	
	Runnable rHideDangxuat = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					llDangxuat.setVisibility(View.GONE);
				}
			});
			
		}
	};
	
	Runnable rEnableSend = new Runnable() {
		
		@Override
		public void run() {
			btnSend.setEnabled(true);
		}
	};
	
	MediaPlayer mp;
	

	String ten;
	TextView title;
	ListView listChat;
	FrameLayout main;
	ArrayList<ObjMsgChat> objMsgChats = new ArrayList<ObjMsgChat>();
	ChatAdapter adapter;

	// layout chat
	EditText edtChat;
	ImageButton btnChupanh;
	Button btnSend;
	ImageView btnClear;

	Handler mHandler = new Handler();

	String KEY_SOFTWARE = "kksdfuy97dfsdfjh23uibjdbsjfsdf";

	String tokenChuaMd5, tokenMd5;

	ObjKhachhang objKhachhang = new ObjKhachhang();
	
	Runnable rP = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					progressBar.setVisibility(View.GONE);
				}
			});
		}
	};
	
	ViewGroup llDangxuat;
	TextView txtDangxuat;
	Thread tr;
	Runnable rDangxuat = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					llDangxuat.setVisibility(View.GONE);
				}
			});
			
		}
	};
	
	Runnable rHis = new Runnable() {
		
		@Override
		public void run() {
			getHash();
		}
	};
	
	void updateListMsg() {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				objMsgChats.clear();
				objMsgChats.addAll(db.getAllMsgHis(objKhachhang.getId()));
				adapter.notifyDataSetChanged();
				listChat.setSelection(adapter.getCount()-1);
			}
		});
	}
	
	ViewGroup llChat;
	TextView llChatDis;
	private BroadcastReceiver mReceiver;
	
	// layout new msg khi dang cuon len tren
	LinearLayout llNewMsgTop;
	Button btnScroll;
	private boolean isLastestMsg = true;
	
	// show dialog chon anh
	Dialog dChoose;
	
	// chon anh
	private static final int PICK_PHOTO = 100;
	private static final int CAPTURE_PHOTO = 200;

	Uri mCapturedImageURI;
	String selectedPath;
	Uri selectedImageUri;
	
	

	String TEMP_TAKE_IMAGE = Common.SDCARD_IMAGE + "tmp_take_photo.jpg";
	String file_path;
	
	// check ket noi
	// layout ket noi
	RelativeLayout llKetnoi;
	TextView txtKetnoi;
	Runnable rHideKetnoi = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					llKetnoi.setVisibility(View.GONE);
//					llKetnoi.setAnimation(pullUp);
				}
			});
			
		}
	};
	
	DisplayImageOptions options = new DisplayImageOptions.Builder()
								.cacheInMemory(true).cacheOnDisc(true)
								.bitmapConfig(Config.RGB_565)
								.showImageForEmptyUri(R.drawable.defaul_avatar)
								.build();
	
	View h;
	TextView titleP;
	MyCircleImageView imgAvatar;
	
	String msgId;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat_new);

		preferenceHelper = new PreferenceHelper(this);
		db = new MySQLiteHelper(ChatNewActivity.this);

		main = (FrameLayout) findViewById(R.id.main);

		KeyboardHelper.setupUI(ChatNewActivity.this, main);
		
		objKhachhang = getIntent().getParcelableExtra("khachhang");
		
		// xac dinh la dang o man hinh chat
		Common.onScreenChat = true;
		Common.isChatting = objKhachhang.getId();
		
		preferenceHelper.setAvatarKH(objKhachhang.getUrlAvatar());
		
		MD5Token();
		//update tin nhan cuoi la da doc

		db.updateLastMsgDadoc(objKhachhang.getId(), 0);
		
		url = objKhachhang.getUrlDangxem();
		
		
		dsDaxem = objKhachhang.getDsDaxem();
		
		Log.i("vChat","Dang xem: "+url);
		

		title = (TextView) findViewById(R.id.title);
		icOnline = (ImageView) findViewById(R.id.ic_online);
		btnBack = (Button) findViewById(R.id.btn_back);
		progressBar = (ProgressBar) findViewById(R.id.progress_bar);
		
		llChat = (ViewGroup) findViewById(R.id.ll_chat);
		llChatDis = (TextView) findViewById(R.id.ll_chat_dis);
		
		// check ket noi socket
		llKetnoi = (RelativeLayout) findViewById(R.id.ll_ketnoi);
		txtKetnoi = (TextView) findViewById(R.id.txt_ketnoi);
		
		// check on off
		llDangxuat = (ViewGroup) findViewById(R.id.ll_dangxuat);
		txtDangxuat = (TextView) findViewById(R.id.txt_kh_dangxuat);
		// new msg khi khong o cuoi doan chat
		llNewMsgTop = (LinearLayout) findViewById(R.id.ll_tinnhan_moi);
		btnScroll = (Button) findViewById(R.id.btn_scroll);
		
		//header
		h = (View) findViewById(R.id.ll_product);
		titleP = (TextView) findViewById(R.id.titleP);
		imgAvatar = (MyCircleImageView) findViewById(R.id.avatar_khach_hang);
		txtSanpham = (TextView) findViewById(R.id.txt_sanpham);
		
		header = (ViewGroup) findViewById(R.id.header);

		
		btnBack.setVisibility(View.VISIBLE);
		
		
		icOnline.setVisibility(View.VISIBLE);
		
		// new msg ko phai cua mình
		llNewMsg = (LinearLayout) findViewById(R.id.ll_new_msg);
		txtTen = (TextView) findViewById(R.id.txt_name);
		txtMsg = (TextView) findViewById(R.id.txt_msg);
		
		pullDown = AnimationUtils.loadAnimation(this, R.anim.slide_down);
		pullUp = AnimationUtils.loadAnimation(this, R.anim.slide_up);
		fadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein);
		fadeOut = AnimationUtils.loadAnimation(this, R.anim.fadeout);
		
		mp = MediaPlayer.create(ChatNewActivity.this, R.raw.result);
		
		

		

		// layout chat
		btnChupanh = (ImageButton) findViewById(R.id.btn_chupanh);
		edtChat = (EditText) findViewById(R.id.edt_chat);
		btnSend = (Button) findViewById(R.id.btn_send);
		btnClear = (ImageView) findViewById(R.id.btn_clears);
		
		
		if (objKhachhang.getOnline() == 0) {
			icOnline.setImageResource(R.drawable.ic_offline);
		} else {
			icOnline.setImageResource(R.drawable.ic_online);
		}

		
		listChat = (ListView) findViewById(R.id.list_chat);
		addBlankItem();
		addHeader();
		
		adapter = new ChatAdapter(ChatNewActivity.this, objMsgChats);
		listChat.setAdapter(adapter);
		
		adapter.notifyDataSetChanged();
		if(listChat.getAdapter().getCount()>1)
			listChat.setSelection(listChat.getAdapter().getCount() - 1);
		getHash();
		
		progressBar.setVisibility(View.VISIBLE);
		mHandler.removeCallbacks(rP);
		mHandler.postDelayed(rP, 60000);
			
		
		nhapTinnhan();
		init();
		reciveBroadCast();
		setFont();
	}
	
	private void MD5Token(){
		tokenChuaMd5 = KEY_SOFTWARE + "|" + preferenceHelper.getAdminId() + "|"+ objKhachhang.getId();
		Log.i("vChat","CHUA MD5 :"+ (KEY_SOFTWARE + "|" + preferenceHelper.getAdminId()+ "|" + objKhachhang.getId()));
		tokenMd5 = Utils.MD5(tokenChuaMd5);
		Log.i("vChat", "TOKEN :" + tokenMd5);
	}
	
	private void showAnimationNewMsg(){
		mHandler.removeCallbacks(rHide);
		mHandler.removeCallbacks(rShow);
		mHandler.postDelayed(rShow, 1000);
		mHandler.postDelayed(rHide, 3000);
	}
	
	
	private void playRingtone(){
		try {
			mp.prepare();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mp.start();
	}

	private void addBlankItem(){
		LayoutInflater inflater = getLayoutInflater();
		View v = (View) inflater.inflate(R.layout.header_blank, listChat, false);
		listChat.addHeaderView(v, null, false);
	}
	
	private void addHeader() {
		if (!url.equals("")){
			if (objKhachhang.getDsDaxem().equals("")){
				if (url.length() > 30){
					txtSanpham.setText(url.substring(0, 30)+"...");
				} else {
					txtSanpham.setText(url);
				}
			} else {
				if (dsDaxem.length() > 40){
					txtSanpham.setText(dsDaxem.substring(0, 37)+"...");
				} else {
					txtSanpham.setText(dsDaxem);
				}
			}
		} else {
			txtSanpham.setText("Chưa xem sản phẩm.");
		}
		
		
		ImageLoader.getInstance().displayImage(objKhachhang.getUrlAvatar(), imgAvatar, options);
		

		titleP.setTypeface(Utils.getTypefaceMedium(ChatNewActivity.this));
		txtSanpham.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		
		h.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!url.equals("")){
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(browserIntent);
				} else {
					
				}
				
			}
		});
	}

	private void nhapTinnhan() {
		edtChat.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2,
					int arg3) {
				if (s.toString().length() > 0) {
					btnClear.setVisibility(View.VISIBLE);
				} else {
					btnClear.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});

		edtChat.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				actionSend();
				return true;
			}
		});

	}

	void actionSend() {
		sendMsgToServer(objKhachhang.getId(), edtChat.getText().toString());
		addMsgToDB();
	}

	private void setFont() {
		edtChat.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		btnSend.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		txtMsg.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		txtTen.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		txtDangxuat.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		txtKetnoi.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
	}

	private void init() {
		
		listChat.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if(firstVisibleItem+visibleItemCount<totalItemCount) {
					isLastestMsg = false;
				} else {
					isLastestMsg = true;
					if(isShowingBtnNew == true){
						updateListMsg();
					}
					hiddenButtonLastestMsg();
				}
				
			}
		});
		
		
		if (objKhachhang.getName().length() > 10){
			title.setText(objKhachhang.getName().substring(0, 10)+"...");
		} else {
			title.setText(objKhachhang.getName());
		}
		
		btnHoatdong = (Button) findViewById(R.id.btn_hoatdong);
		
		btnBack.setOnTouchListener(this);
		btnHoatdong.setOnTouchListener(this);
		edtChat.setOnTouchListener(this);
		btnClear.setOnClickListener(this);
		btnSend.setOnClickListener(this);
		btnChupanh.setOnClickListener(this);
		btnScroll.setOnClickListener(this);
	}

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				closeActivity();
			}
		case R.id.btn_hoatdong:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if (h.getVisibility() == View.VISIBLE){
					h.setVisibility(View.GONE);
					header.setVisibility(View.GONE);
				} else if (h.getVisibility() == View.GONE) {
					h.setVisibility(View.VISIBLE);
					header.setVisibility(View.VISIBLE);
				}
			}
			break;
		case R.id.edt_chat:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				edtChat.requestFocus();
				edtChat.setFocusable(true);
			}
		default:
			break;
		}
		return false;
	}

	void closeActivity() {
		finish();
		onShow = true;
		overridePendingTransition(0, R.anim.trans_right_out);
	}

	@Override
	public void onBackPressed() {
		closeActivity();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_clears:
			edtChat.setText("");
			break;

		case R.id.btn_send:
			actionSend();
			btnSend.setEnabled(false);
			break;
		case R.id.btn_scroll:
			hiddenButtonLastestMsg();
			smoothScrollToBottom();
			break;
		case R.id.btn_chupanh:
			showDialogChonanh();
			break;
			
		case R.id.btn_capture_image:
			dChoose.dismiss();
			takeImage();
			break;
		case R.id.btn_choose_image:
			dChoose.dismiss();
			openGallery();
			break;
		case R.id.btn_thoat:
			dChoose.dismiss();
			break;

		default:
			break;
		}
	}
	
	
	private void addMsgToDB() {
		if (!edtChat.getText().toString().equals("")) {
			
			ObjMsgChat objMsgChat = new ObjMsgChat(preferenceHelper.getAdminId(), "", edtChat.getText().toString(), "");
			objMsgChat.setType("text");
			
			msgId = String.valueOf(Common.getCurrentTime()/1000);
			
			String lastMsg = edtChat.getText().toString();
					
			objKhachhang.setLastMessage(lastMsg);
			objKhachhang.setTimeLastMessage(""+(Common.getCurrentTime()/1000));
			
			edtChat.setText("");
			listChat.setSelection(adapter.getCount() - 1);
			db.insertMSG(objMsgChat, objKhachhang.getId(), Common.SENDING, msgId);
			updateListMsg();
			db.updateHischat(objKhachhang);
			btnSend.setEnabled(false);
			mHandler.postDelayed(rEnableSend, 1000);
		}
	}
	
	void addMyMsg(){
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				objMsgChats.clear();
				objMsgChats.addAll(db.getAllMsgHis(objKhachhang.getId()));
				adapter.notifyDataSetChanged();
				listChat.setSelection(adapter.getCount()-1);
			}
		});
		
	}
	
	private void addMsgImage(String url) {
			
			ObjMsgChat objMsgChat = new ObjMsgChat(preferenceHelper.getAdminId(), "", "", url);
			
			objMsgChat.setType("image");
			msgId = String.valueOf(Common.getCurrentTime()/1000);
			objMsgChats.add(objMsgChat);
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					listChat.setSelection(objMsgChats.size());
				}
			});
			
			db.insertMSG(objMsgChat, objKhachhang.getId(), Common.SENDING, msgId);
			btnSend.setEnabled(false);
			mHandler.postDelayed(rEnableSend, 700);
	}

	private void getHistorychat(String hash) {

		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback(){

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200){
					try {
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								progressBar.setVisibility(View.GONE);
							}
						});
						
						
						int status = re.getInt("status");
						if (status == 1) {
							db.deteleAllRecord(objKhachhang.getId());
							JSONArray listMsg = re.getJSONArray("msg");

							Log.i("vChat", "List Msg:" + listMsg);
//							Log.i("Thientv","====================1");
							for (int i = 0; i < listMsg.length(); i++) {
								JSONObject msg = listMsg.getJSONObject(i);
								int fromTo = msg.getInt("cha_owner_id");
								String contentMsg = msg.getString("cha_message");
								String msgID = msg.getString("cha_id");
								String time = msg.getString("cha_time");
								String cha_key = msg.getString("cha_key");
								
//								Log.i("Thientv","====================2");
								
								final ObjMsgChat objMsgChat = new ObjMsgChat();

								if (msg.has("type")) {
									if (msg.getString("type").equals("image")){
										objMsgChat.setUrlImageKH(contentMsg);
										objMsgChat.setType("image");
									} else {
										objMsgChat.setUrlImageKH("");
										objMsgChat.setType("text");
									}
								} else {
									objMsgChat.setUrlImageKH("");
									objMsgChat.setType("text");
								}
								
								
//								Log.i("Thientv","====================3");
								
								objMsgChat.setMsgID(msgID);
								objMsgChat.setUrlAvatarKhachhang(objKhachhang.getUrlAvatar());
								objMsgChat.setFromId(String.valueOf(fromTo));
								objMsgChat.setContent(contentMsg);
								objMsgChat.setTime(Integer.valueOf(time));
								objMsgChat.setTenKhachHang(objMsgChat.getTenKhachHang());
								objMsgChat.setStatus(1);
//								objMsgChats.add(objMsgChat); 
//								msgId = String.valueOf(Common.getCurrentTime()/1000);
								msgId = cha_key;
								
								
								runOnUiThread(new Runnable() {
									
									@Override
									public void run() {
										objMsgChats.add(objMsgChat);
										adapter.notifyDataSetChanged();
										if(adapter.getCount()>1)
											listChat.setSelection(adapter.getCount() - 1);
									}
								});
								
							}
						} else {
							Log.i("vChat", "ERROR: "+re.toString());
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									progressBar.setVisibility(View.GONE);
								}
							});
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							progressBar.setVisibility(View.GONE);
						}
					});
				}
			}
			@Override
			public void onFailure(Exception e) {
			}
		});
		httpBasicClientHelper.getHistoryChat(Integer.valueOf(preferenceHelper.getAdminId()),Integer.valueOf(objKhachhang.getId()), hash, 1, 1);
	}

	
	private void getHash() {
		if(hash==null || hash.equals("")) {
			HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback(){
	
				@Override
				public void onSuccess(HttpResponse httpResponse, JSONObject re) {
					int statusCode = httpResponse.getStatus();
					if (statusCode == 200){
						try {
							String error = re.getString("error");
							Log.i("vChat", "HASH: "+re.toString());
							if (!error.equals("")) {
								runOnUiThread(new Runnable() {
									
									@Override
									public void run() {
										Toast.makeText(ChatNewActivity.this,"Không kết nối được với máy chủ.",Toast.LENGTH_SHORT).show();
									}
								});
								
							} else {
								hash = re.getString("hash");
								Log.i("vChat", "HASH CHAT: " + hash);
								getHistorychat(hash);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					} else { }
				}
	
				@Override
				public void onFailure(Exception e) {
				}
			});
			httpBasicClientHelper.getHash(Integer.valueOf(objKhachhang.getId()),Integer.valueOf(preferenceHelper.getAdminId()), preferenceHelper.getHashSetting(), 1);
		} else {
			getHistorychat(hash);
		}
	}
	
	public String sendMsgToServer(String _kh_id, String _msg) {
		long vcg =  Common.getCurrentTime();
		
		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback(){

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200){
					Log.i("vChat", "SENDMSG: "+re.toString());
					try {
						String error = re.getString("error");
						if (error.equals("")) {
							
							Log.i("SendMSG", "Gui thanh cong");
							status = "1";
							db.updateStatusMsg(msgId, 1);
							/*mHandler.removeCallbacks(rAdd);
							mHandler.postDelayed(rAdd, 200);*/
							addMyMsg();
						} else {
							status = "0";
							db.updateStatusMsg(msgId, 2);
							updateListMsg();
							actionSend();
							Log.i("SendMSG", "Chua gui dc tin nhan");
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									Toast.makeText(ChatNewActivity.this, "Chưa gửi được tin nhắn.", Toast.LENGTH_SHORT).show();
								}
							});
							
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					db.updateStatusMsg(msgId, 2);
					updateListMsg();
					actionSend();
				}
			}

			@Override
			public void onFailure(Exception e) {
				db.updateStatusMsg(msgId, 2);
				updateListMsg();
				actionSend();
			}
			
		});
		
		if (!edtChat.getText().toString().equals("")){
			httpBasicClientHelper.sendChatMsg(
					Integer.valueOf(preferenceHelper.getAdminId()),
					Integer.valueOf(_kh_id), 
					hash, 
					"text", 
					1,
					_msg, 
					preferenceHelper.getUserName(), 
					vcg, 
					vcg/1000);
			Log.i("DATA", "VGC gui di : "+vcg);
			Common.VGC = vcg;
		}
		
		return status;
	}
	
	
	private void sendMsgImage(String url) {
		
		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback(){

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200){
					try {
						String error = re.getString("error");
						if (error.equals("")) {
							Log.i("SendMSG", "Gui thanh cong");
							status = "1";
							db.updateStatusMsg(msgId, 1);
							updateListMsg();
						} else {
							status = "0";
							db.updateStatusMsg(msgId, 2);
							updateListMsg();
							Log.i("SendMSG", "Chua gui dc tin nhan");
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									Toast.makeText(ChatNewActivity.this, "Chưa gửi được tin nhắn.", Toast.LENGTH_SHORT).show();
								}
							});
							
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					db.updateStatusMsg(msgId, 2);
					updateListMsg();
				}
			}

			@Override
			public void onFailure(Exception e) {
				db.updateStatusMsg(msgId, 2);
				updateListMsg();
			}
			
		});
		
			long vcg =  Common.getCurrentTime()/1000;
			httpBasicClientHelper.sendChatMsg(Integer.valueOf(preferenceHelper.getUserId()),
					Integer.valueOf(objKhachhang.getId()), hash, "image", 1,
					url, objKhachhang.getName(), vcg, vcg);
			Log.i("DATA", "VGC gui di : "+vcg);
			Common.VGC = vcg;
		
	}
	
	
	
	
	

	@Override
	protected void onPause() {
		super.onPause();
//		socketIO.disconnect();
		Log.i("Socket", "ONSHOW: "+onShow);
		if (onShow == true){
			if (isNoti == true){
				if (isNoti == true){
					if (tr != null){
						tr.interrupt();
					}
					socketIO.disconnect();
				} else {
					
				}
			}
		} else {
			// gui 1 broad cast cho thang main
			Intent broadcastIntent = new Intent();
			broadcastIntent.setAction(Common.DISCONECT);
			sendBroadcast(broadcastIntent);
			Log.i("Socket", "send broadcast disconnect");
			onPause = true;
			cancelHandler();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		if (Common.toNotify == true){
			Log.i("Socket", "Goi lại connect socket khi click notify");
			isNoti = true;
			// gui 1 broad cast cho thang main
			connectSocket();
			
			Common.toNotify = false;
			
		} else {
			isNoti = false;
			if (onPause == true){
				
				Log.i("Socket", "Goi lại connect socket trong trang chat");
				
				// gui 1 broad cast cho thang main
				Intent broadcastIntent = new Intent();
				broadcastIntent.setAction(Common.CONNECT);
				sendBroadcast(broadcastIntent);
			} else {
				
				
				if (onShow == true){
					
				} else {
					/*mHandler.removeCallbacks(rHis);
					mHandler.postDelayed(rHis, 300);*/
				}
			}
		
		onPause = false;
		}
		
			
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i("vChat", "Trang thai destroy");
		cancelHandler();
		
		
		if (isNew == true){
			Common.onScreenChat = true;
		} else {
			Common.isChatting = "";
			Common.onScreenChat = false;
		}
		
		unregisterReceiver(mReceiver);
	}
	
	private void cancelHandler(){
		mHandler.removeCallbacks(rHideDangxuat);
		mHandler.removeCallbacks(rShowDangxuat);
		mHandler.removeCallbacks(rDangxuat);
		mHandler.removeCallbacks(rShow);
		mHandler.removeCallbacks(rHide);
		mHandler.removeCallbacks(rHis);
		mHandler.removeCallbacks(rHideKetnoi);
		mHandler.removeCallbacks(rEnableSend);
		adapter.removeHanlder();
		mHandler.removeCallbacksAndMessages(null);
	}
	
	private void reciveBroadCast(){
		IntentFilter intentFilter = new IntentFilter();
		
		
		 intentFilter.addAction(Common.CHAT);
		 intentFilter.addAction(Common.CHAT_NEWMSG);
		 
		 intentFilter.addAction(Common.CONNECTTING);
		 intentFilter.addAction(Common.CONNECTED);
		 
		 intentFilter.addAction(Common.FINSH_CHAT);
		 intentFilter.addAction(Common.CONNECT);
		 intentFilter.addAction(Common.MY_ADD);
		    
		    mReceiver = new BroadcastReceiver() {
				
				@Override
				public void onReceive(Context context, final Intent intent) {
					String action = intent.getAction();
					if (action.equals(Common.CHAT)){
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								runOnUiThread(new Runnable() {
									
									@Override
									public void run() {
										if(!isLastestMsg) {
											showButtonLastestMsg();
											isShowingBtnNew = true;
											Log.i("DATA", "kieu tin nhan moi");
										} else {
											objMsgChats.addAll(db.getAllMsgHis(objKhachhang.getId()));
											adapter.notifyDataSetChanged();
											goToLastestMsg();
										}
										
									}
								});
								
//								adapter.notifyDataSetChanged();
							}
						});
						Log.i("vChat", "Nhan duoc broadcast chat");
					} else if (action.equals(Common.CHAT_NEWMSG)) {
						Log.i("vChat", "Nhan duoc broadcast chat new msg");
						
						
						llNewMsg.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View view) {
								
								Log.i("vChat", "Trong man hinh chat click new msg");
								ChatNewActivity.onShow = true;
								isNew = true;
								ObjKhachhang objKhachhang = new ObjKhachhang();
								objKhachhang = intent.getParcelableExtra("khachhang");
								Intent t = new Intent(ChatNewActivity.this, ChatNewActivity.class);
								t.putExtra("khachhang", objKhachhang);
								finish();
								startActivity(t);
							}
						});
						
						
						
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								
								mHandler.removeCallbacks(rHide);
								mHandler.removeCallbacks(rShow);
								
								if (llNewMsg.getVisibility() == View.VISIBLE){
									llNewMsg.setVisibility(View.GONE);
								}
								
								showAnimationNewMsg();
								if (preferenceHelper.getSettingRingtone() == 1){
									playRingtone();
								}
								ObjMsgChat objMsgChatNew = new ObjMsgChat();
								objMsgChatNew = intent.getParcelableExtra("objMsg");
								txtTen.setText(objMsgChatNew.getTenKhachHang());
								txtMsg.setText(objMsgChatNew.getContent());
								
							}
						});
						
						
					} else if (action.equals(Common.CONNECTTING)) {
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								llKetnoi.setVisibility(View.VISIBLE);
								llKetnoi.setBackgroundColor(getResources().getColor(R.color.color_cam));
								txtKetnoi.setText("Đang kết nối...");
							}
						});
					} else if (action.equals(Common.CONNECTED)) {
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								llKetnoi.setBackgroundResource(R.drawable.background_transition);
								TransitionDrawable background = (TransitionDrawable) llKetnoi.getBackground();
								background.startTransition(100);
								txtKetnoi.setText("Kết nối thành công!");
								mHandler.postDelayed(rHideKetnoi, 2000);
							}
						});
					} else if (action.equals(Common.FINSH_CHAT)) {
						finish();
					} else if (action.equals(Common.CONNECT)) {
						
					} else if (action.equals(Common.MY_ADD)) {
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								Log.i("DATA", "nhay vào để add tin nhắn trên nhiều thiết bị");
								objMsgChats.addAll(db.getAllMsgHis(objKhachhang.getId()));
								adapter.notifyDataSetChanged();
								goToLastestMsg();
							}
						});
					}
				}
			};
			
			// register
			this.registerReceiver(mReceiver, intentFilter);
	}
	
	private void hiddenButtonLastestMsg() {
		isShowingBtnNew = false;
		llNewMsgTop.setVisibility(View.GONE);
	}
	
	private void showButtonLastestMsg(){
		llNewMsgTop.setVisibility(View.VISIBLE);
	}
	
	private void goToLastestMsg() {
		listChat.setSelection(objMsgChats.size()-1);
	}
	
	private void smoothScrollToBottom(){
		listChat.smoothScrollToPosition(objMsgChats.size());
		updateListMsg();
		
	}
	
	// show dialog sau khi them thanh cong
		public void showDialogChonanh() {
			onShow = true;
			dChoose = new Dialog(this, R.style.DialogSlideAnim);
			dChoose.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dChoose.setContentView(R.layout.dialog_choose_photo);

			Button btnChonanh = (Button) dChoose
					.findViewById(R.id.btn_choose_image);
			Button btnChupanh = (Button) dChoose
					.findViewById(R.id.btn_capture_image);

			Button btnThoat = (Button) dChoose.findViewById(R.id.btn_thoat);
			
			btnChonanh.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
			btnChupanh.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
//			btnThoat.setTypeface(Utils.getTypefaceBold(ChatActivity.this), Typeface.BOLD);
			
			dChoose.show();
			dChoose.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dChoose.setCanceledOnTouchOutside(true);
			dChoose.getWindow().setGravity(Gravity.BOTTOM);
			dChoose.show();

			// setonclick
			btnChonanh.setOnClickListener(this);
			btnChupanh.setOnClickListener(this);
			btnThoat.setOnClickListener(this);
		}
		
		// chon anh
		public void openGallery() {
			File ff = new File(TEMP_TAKE_IMAGE);
			if (ff.exists())
				ff.delete();
			Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
			photoPickerIntent.setType("image/*");
			startActivityForResult(photoPickerIntent, PICK_PHOTO);
		}
		
		// chup anh
		public void takeImage() {
			String fileName = "temp.jpg";
			ContentValues values = new ContentValues();
			values.put(MediaStore.Images.Media.TITLE, fileName);
			mCapturedImageURI = getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
			startActivityForResult(intent, CAPTURE_PHOTO);
		}

		@SuppressWarnings({ "deprecation", "unused" })
		@Override
		protected void onActivityResult(int requestCode, int resultCode,
				Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			if (resultCode == RESULT_OK) {
				switch (requestCode) {
				case PICK_PHOTO:
					Uri u = (Uri) data.getData();
					String[] filePathColumn = { MediaStore.Images.Media.DATA };
					Cursor cursor = getContentResolver().query(u, filePathColumn,
							null, null, null);
					cursor.moveToFirst();
					int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
					file_path = cursor.getString(columnIndex);

					Log.i("DATA", "File upload :" + file_path);
					
					
					
					Bitmap bm = DecodeUtils.decode(ChatNewActivity.this,
							Uri.parse(file_path), 800, 800);
					
					Log.i("vChat", "Width: "+bm.getWidth() + "Height: "+bm.getHeight());
					
					if (bm == null) {
						Toast.makeText(ChatNewActivity.this,
								"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
						return;
					}
					
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					bm.compress(Bitmap.CompressFormat.JPEG, 75, stream);
					byteArray = stream.toByteArray();

					// upload image
					addMsgImage("file://"+file_path);
					uploadImage();
					try {
						if (cursor != null){
							cursor.close();	
						}
					} catch (IllegalStateException e) {
						e.printStackTrace();
					}

					break;
				case CAPTURE_PHOTO:
					String[] projection = { MediaStore.Images.Media.DATA };
					Cursor cursor1 = managedQuery(mCapturedImageURI, projection,
							null, null, null);
					int column_index_data = cursor1
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					cursor1.moveToFirst();
					file_path = cursor1.getString(column_index_data);
					Log.i("DATA", "File upload :" + file_path);

					Bitmap bm1 = DecodeUtils.decode(ChatNewActivity.this,
							Uri.parse(file_path), 800, 800);
					if (bm1 == null) {
						Toast.makeText(ChatNewActivity.this,
								"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
						return;
					}
					
					ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
					bm1.compress(Bitmap.CompressFormat.JPEG, 75, stream1);
					byteArray = stream1.toByteArray();
					
//					imgTungbuoc.setScaleType(ScaleType.CENTER_CROP);
//					imgTungbuoc.setImageBitmap(bm1);

					addMsgImage("file://"+file_path);
					uploadImage();
					try {
						if (cursor1 != null){
							cursor1.close();
						} 
					} catch (IllegalStateException e) {
						e.printStackTrace();
					}
					break;
				}
			}
		}
		
		
		@Override
		@Deprecated
		public void startManagingCursor(Cursor c) {
			if (Build.VERSION.SDK_INT < VERSION_CODES.HONEYCOMB) {
		        super.startManagingCursor(c);
		    }
		}

		void uploadImage() {
			RequestParams params = new RequestParams();
			params.put("sso_id", preferenceHelper.getUserId());
			params.put("hash", preferenceHelper.getHash());
			
			params.put("picture", new ByteArrayInputStream(byteArray), "image.jpg");

			AsyncHttpClient client = new AsyncHttpClient();
			client.post("http://vchat.vn/service/upload_image.php", params,
					new MyJsonHttpResponseHandler() {

						@Override
						public void onFailure(Throwable error) {
							super.onFailure(error);
							Toast.makeText(ChatNewActivity.this,
									"Request failed.", Toast.LENGTH_SHORT).show();
							db.updateStatusMsg(msgId, 2);
							updateListMsg();
						}

						@Override
						public void onSuccess(JSONObject re) {
							try {
								String error = re.getString("error");
								
								if (!error.equals("")){
									Log.i("DATA", "File qua lon");
									
									Toast.makeText(ChatNewActivity.this, "File ảnh quá lớn.", Toast.LENGTH_SHORT).show();
								} else {
									String data = re.getString("data");
									Log.i("DATA", "URL tra ve: "+data);
									sendMsgImage(data);
								}
								
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}

					});
		}
	
	public void connectSocket() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				llKetnoi.setVisibility(View.VISIBLE);
				llKetnoi.setBackgroundColor(getResources().getColor(
						R.color.color_cam));
				txtKetnoi.setText("Đang kết nối...");

				if (Common.onScreenChat == true) {
					// send broadcast show dang ket noi
					Intent broadcastIntent = new Intent();
					broadcastIntent.setAction(Common.CONNECTTING);
					sendBroadcast(broadcastIntent);
				}
			}
		});
		tr = new Thread(new Runnable() {

			@SuppressLint("NewApi")
			@Override
			public void run() {
				try {
					try {
						SocketIO.setDefaultSSLSocketFactory(SSLContext
								.getDefault());
					} catch (NoSuchAlgorithmException e1) {
						e1.printStackTrace();
					}
					socketIO = new SocketIO(URL);
					socketIO.connect(new IOCallback() {

						@Override
						public void onMessage(JSONObject arg0,
								IOAcknowledge arg1) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onMessage(String arg0, IOAcknowledge arg1) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onError(SocketIOException message) {
							Log.e("Socket", "ket noi bi loi----------:"
									+ message.toString());
							connectSocket();
						}

						@Override
						public void onDisconnect() {
							Log.e("Socket", "Da dut ket noi----------");

							if (isNoti == true) {

							} else {
								if (onFinish == true) {
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											llKetnoi.setVisibility(View.VISIBLE);
											llKetnoi.setBackgroundColor(Color.BLACK);
											txtKetnoi.setText("Mất kết nối");
										}
									});
								} else {
									if (onPause == true) {

									} else {
										connectSocket();
									}
								}
							}

						}

						@Override
						public void onConnect() {
							Log.e("Socket", "Ket noi thanh cong----------");
							socketIO.emit("join",
									preferenceHelper.getDataJoin());
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									llKetnoi.setBackgroundResource(R.drawable.background_transition);
									TransitionDrawable background = (TransitionDrawable) llKetnoi
											.getBackground();
									background.startTransition(100);
									txtKetnoi.setText("Kết nối thành công!");
									mHandler.postDelayed(rHideKetnoi, 2000);
								}
							});
						}

						@Override
						public void on(String event, IOAcknowledge arg1,
								Object... args) {
							System.out.println("Server triggered event '"
									+ event + "'");
							Object[] arguments = args;

							if (event.equals("chat")) {
								String json = arguments[0].toString();
								Log.i("vChat", json.toString());
								try {
									JSONObject jos = new JSONObject(json);

									JSONObject jo = jos.getJSONObject("data");

									int sendId = jo.getInt("send_id");
									final String name = jo.getString("name");
									final String content = jo.getString("text");
									int time = jo.getInt("time");
									String type, urlImage;
									if (jo.has("type")) {
										type = jo.getString("type");
										urlImage = content;
										if (type.equals("image")) {
											type = "image";
											urlImage = content;
										} else {
											type = "text";
											urlImage = "";
										}

									} else {
										type = "text";
										urlImage = "";
									}

									ObjMsgChat objMsgChat = new ObjMsgChat();
									objMsgChat.setUrlImageKH(urlImage);
									objMsgChat.setFromId(String.valueOf(sendId));
									objMsgChat.setContent(content);
									objMsgChat.setUrlAvatarKhachhang("");
									objMsgChat.setTenKhachHang(name);
									objMsgChat.setTime(time);
									objMsgChat.setType(type);

									final ObjKhachhang objKhachhang = new ObjKhachhang();
									objKhachhang.setUrlAvatar("");
									objKhachhang.setName(name);
									objKhachhang.setAddress("");
									objKhachhang.setDsDaxem("");
									objKhachhang.setId(String.valueOf(sendId));
									objKhachhang.setTxtWebsite("");
									objKhachhang.setOnline(1);
									objKhachhang.setUrlDangxem("");
									objKhachhang.setTimeLastMessage(String
											.valueOf(time));
									objKhachhang.setLastMessage(content);
									msgId = String.valueOf(Common
											.getCurrentTime() / 1000);
									db.insertMSG(objMsgChat,
											objMsgChat.getFromId(),
											Common.SENDED, msgId);

									Log.i("vChat", "Co o trong man hinh chat :"
											+ Common.onScreenChat);

									if (Common.onScreenChat == true) {
										if (Common.isChatting.equals(objMsgChat
												.getFromId())) {

											runOnUiThread(new Runnable() {

												@Override
												public void run() {
													objMsgChats.addAll(db
															.getAllMsgHis(objKhachhang
																	.getId()));
													adapter.notifyDataSetChanged();
													goToLastestMsg();
												}
											});

										} else {
											Log.i("vChat",
													"Nhan duoc broadcast chat new msg");

											llNewMsg.setOnClickListener(new OnClickListener() {

												@Override
												public void onClick(View view) {

													Log.i("vChat",
															"Trong man hinh chat click new msg");
													ChatNewActivity.onShow = true;
													isNew = true;
													Intent t = new Intent(
															ChatNewActivity.this,
															ChatNewActivity.class);
													t.putExtra("khachhang",
															objKhachhang);
													finish();
													startActivity(t);
												}
											});

											runOnUiThread(new Runnable() {

												@Override
												public void run() {
													showAnimationNewMsg();
													if (preferenceHelper
															.getSettingRingtone() == 1) {
														playRingtone();
													}
													txtTen.setText(objKhachhang
															.getName());
													txtMsg.setText(objKhachhang
															.getLastMessage());

												}
											});
										}
									} else {

									}

								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}

						}
					});
				} catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});

		tr.start();
	}

	
	public void updateUI(){
		objMsgChats = db.getAllMsgHis(objKhachhang.getId());
		adapter = new ChatAdapter(ChatNewActivity.this, objMsgChats);
		listChat.setAdapter(adapter);
		listChat.setSelection(adapter.getCount()-1);
	}
	
}
